{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "445affec-225c-42b2-9397-8ce6757c436c",
   "metadata": {},
   "source": [
    "# **Working with JSON Data**\n",
    "\n",
    "### **What's covered in this notebook?**\n",
    "\n",
    "1. Introduction to JSON\n",
    "    - Why JSON?\n",
    "    - JSON vs CSV\n",
    "    - Data Types supported by JSON\n",
    "    - Example of a Simple JSON Document\n",
    "    - Reading a JSON - json.load() vs json.loads()\n",
    "    - Accessing JSON Data\n",
    "    - Modifying JSON Data\n",
    "    - Writing a JSON - json.dump() vs json.dumps()\n",
    "2. Understanding Nested JSON Structures\n",
    "    - Reading a Nested JSON File\n",
    "    - Iterating over JSON Data\n",
    "    - Extracting Data From Nested JSON\n",
    "    - Adding and Updating Fields\n",
    "    - Handling Missing Keys using .get() Method\n",
    "    - Filtering JSON Data\n",
    "    - Writing JSON Data Back to a File\n",
    "3. Advanced JSON Operations\n",
    "    - Sorting JSON Data\n",
    "    - Merging Two JSON Objects\n",
    "4. Handling JSON Data from APIs\n",
    "    - Fetching JSON from a REST API\n",
    "    - Handling API Errors"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53aee92c-d58d-45af-bde8-1ff22b190127",
   "metadata": {},
   "source": [
    "## **Introduction to JSON**\n",
    "JSON stands for **JavaScript Object Notation.** \n",
    "\n",
    "It is a lightweight data-interchange format that is easy to read and write for humans and efficient for machines to parse and generate. \n",
    "\n",
    "JSON is **commonly used in APIs and real-time data processing.**\n",
    "\n",
    "Even though JSON originated from JavaScript, it is language-independent. Today, almost all programming languages, including Python, Java, C++, Go, and SQL, support JSON.\n",
    "\n",
    "### **Why JSON?**\n",
    "\n",
    "- **Human-readable** – Easy to understand and edit\n",
    "- **Lightweight** – Less data overhead compared to XML\n",
    "- **Universal** – Works across different programming languages\n",
    "- **Structured** – Well-defined format (key-value pairs)\n",
    "- **API Friendly** – Most web services return data in JSON\n",
    "\n",
    "### **JSON vs CSV**\n",
    "JSON is more flexible than CSV, making it ideal for **APIs**, **real-time data**, and **analytics**.\n",
    "\n",
    "| Feature | JSON | CSV | \n",
    "|---------|------|-----|\n",
    "| **Format** | Key-Value Pairs | Rows & Columns | \n",
    "| **Readability** | High | Moderate | \n",
    "| **Nested Structure Support** | ✅ Yes | ❌ No | \n",
    "| **Data Types** | Strings, Numbers, Boolean, Null, Arrays, Objects | Only Strings | \n",
    "| **APIs Use Case** | ✅ Yes | ❌ No | \n",
    "| **File Size** | Moderate | Small | \n",
    "\n",
    "### **Data Types supported by JSON**\n",
    "\n",
    "JSON supports **six** data types:  \n",
    "| Type | Example |\n",
    "|------|---------|\n",
    "| **String** | `\"name\": \"John\"` |\n",
    "| **Number** | `\"age\": 25` |\n",
    "| **Boolean** | `\"is_active\": true` |\n",
    "| **Null** | `\"address\": null` |\n",
    "| **Array** | `\"skills\": [\"Python\", \"SQL\", \"Pandas\"]` |\n",
    "| **Object** (Nested JSON) | `\"location\": {\"city\": \"New York\", \"country\": \"USA\"}` |\n",
    "\n",
    "### **Example of a Simple JSON Document**\n",
    "```json\n",
    "{\n",
    "  \"name\": \"Alice\",\n",
    "  \"age\": 30,\n",
    "  \"is_student\": false,\n",
    "  \"courses\": [\"Data Science\", \"Machine Learning\"],\n",
    "  \"address\": {\n",
    "    \"city\": \"San Francisco\",\n",
    "    \"state\": \"California\",\n",
    "    \"zip\": 94107\n",
    "  }\n",
    "}\n",
    "```\n",
    "**Key Observations:**  \n",
    "1. JSON consists of **key-value pairs**  \n",
    "2. Strings must be in **double quotes** (`\" \"`)  \n",
    "3. JSON supports **arrays** (`[]`) and **nested objects** (`{}`)  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cd200b6-0728-4304-a7ab-ce13ca8fa4da",
   "metadata": {},
   "source": [
    "### **Reading a JSON - json.load() vs json.loads()**\n",
    "\n",
    "- **json.load(file)**: Reads JSON from a file and **converts JSON into a Python dictionary**\n",
    "- **json.loads(string)** → Reads JSON from a string and **converts JSON into a Python dictionary**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "58ed2b11-86e7-46da-913b-c4b7d22fb24e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Alice', 'age': 25, 'city': 'New York'}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "json_string = '{\"name\": \"Alice\", \"age\": 25, \"city\": \"New York\"}'\n",
    "\n",
    "# Convert JSON string to dictionary\n",
    "data = json.loads(json_string)\n",
    "\n",
    "# Print JSON data\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dea52d39-fcd3-4a0f-aece-e955aae00d12",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'employee': {'name': 'John Doe', 'age': 28, 'department': 'Data Science', 'skills': ['Python', 'SQL', 'Pandas'], 'location': {'city': 'Bangalore', 'country': 'India'}}}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "# Open the JSON file\n",
    "with open(\"data/data.json\", \"r\") as file:\n",
    "    data = json.load(file)  # Parse JSON into a Python dictionary\n",
    "\n",
    "# Print JSON data\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "197f31ff-778e-4617-a66e-ae8073d3fd0e",
   "metadata": {},
   "source": [
    "### **Accessing JSON Data**\n",
    "Once JSON is loaded into Python as a dictionary, you can access its elements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a5732871-9e38-469e-9fcf-df39e9982204",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name: John Doe\n",
      "Department: Data Science\n",
      "Skills: ['Python', 'SQL', 'Pandas']\n",
      "City: Bangalore\n"
     ]
    }
   ],
   "source": [
    "# Access employee name\n",
    "print(\"Name:\", data[\"employee\"][\"name\"])\n",
    "\n",
    "# Access employee department\n",
    "print(\"Department:\", data[\"employee\"][\"department\"])\n",
    "\n",
    "# Access skills (Array)\n",
    "print(\"Skills:\", data[\"employee\"][\"skills\"])\n",
    "\n",
    "# Access city (Nested Object)\n",
    "print(\"City:\", data[\"employee\"][\"location\"][\"city\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "857fa935-e4ad-4f1b-b753-30bf8073f51c",
   "metadata": {},
   "source": [
    "### **Modifying JSON Data**\n",
    "You can **add, update, or delete** fields dynamically."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "66c02e18-7153-4074-969e-2ce441ecd867",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Add a new field\n",
    "data[\"employee\"][\"experience\"] = 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "61d47c3a-82a6-491d-ab9b-87a5fd0c878e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Update an existing field\n",
    "data[\"employee\"][\"department\"] = \"Machine Learning\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "bfd6c5ba-3215-4651-9832-e74450618c7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Delete a field\n",
    "del data[\"employee\"][\"age\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa3da690-0038-44b6-8df0-71856fcbd39a",
   "metadata": {},
   "source": [
    "### **Writing a JSON - json.dump() vs json.dumps()**\n",
    "\n",
    "- **json.dump(data, file)**: Writes JSON to a file\n",
    "- **json.dumps(data, indent=4)**: Write JSON to string. Formats JSON with indentation for better readability"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b2c5b452-9421-468b-88dd-d655c945e01c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Updated JSON file saved successfully!\n"
     ]
    }
   ],
   "source": [
    "# Save the updated JSON back to a file\n",
    "with open(\"data/updated_data.json\", \"w\") as file:\n",
    "    json.dump(data, file, indent=4)\n",
    "\n",
    "print(\"Updated JSON file saved successfully!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "d4b6d2f6-2443-4578-8356-8d6c32d1e6f8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "    \"employee\": {\n",
      "        \"name\": \"John Doe\",\n",
      "        \"age\": 28,\n",
      "        \"department\": \"Data Science\",\n",
      "        \"skills\": [\n",
      "            \"Python\",\n",
      "            \"SQL\",\n",
      "            \"Pandas\"\n",
      "        ],\n",
      "        \"location\": {\n",
      "            \"city\": \"Bangalore\",\n",
      "            \"country\": \"India\"\n",
      "        }\n",
      "    }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# Open the JSON file\n",
    "with open(\"data/data.json\", \"r\") as file:\n",
    "    data = json.load(file)  # Parse JSON into a Python dictionary\n",
    "\n",
    "# Convert json to string\n",
    "json_string = json.dumps(data, indent=4)\n",
    "\n",
    "print(json_string)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "dbcde99f-56b6-4013-b684-3e31e0cac2ee",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "    \"employee\": {\n",
      "        \"name\": \"John Doe\",\n",
      "        \"department\": \"Machine Learning\",\n",
      "        \"skills\": [\n",
      "            \"Python\",\n",
      "            \"SQL\",\n",
      "            \"Pandas\"\n",
      "        ],\n",
      "        \"location\": {\n",
      "            \"city\": \"Bangalore\",\n",
      "            \"country\": \"India\"\n",
      "        },\n",
      "        \"experience\": 5\n",
      "    }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# Open the JSON file\n",
    "with open(\"data/updated_data.json\", \"r\") as file:\n",
    "    data = json.load(file)  # Parse JSON into a Python dictionary\n",
    "\n",
    "# Convert json to string\n",
    "json_string = json.dumps(data, indent=4)\n",
    "\n",
    "print(json_string)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "037be130-6060-419a-8f93-af9cc084ff0b",
   "metadata": {},
   "source": [
    "## **Understanding Nested JSON Structures**\n",
    "\n",
    "Real-world JSON is often deeply nested. Let’s learn how to extract, modify, and handle missing keys."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "682b1913-c237-4d26-ab5b-bb918bf5c9dc",
   "metadata": {},
   "source": [
    "### **Reading a Nested JSON File**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "4b49ca3e-f91b-47ed-ac0d-fd3eb66f9b9d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "    \"company\": \"TechCorp\",\n",
      "    \"employees\": [\n",
      "        {\n",
      "            \"id\": 101,\n",
      "            \"name\": \"Alice\",\n",
      "            \"role\": \"Data Analyst\",\n",
      "            \"skills\": [\n",
      "                \"Python\",\n",
      "                \"SQL\"\n",
      "            ],\n",
      "            \"projects\": {\n",
      "                \"current\": \"Sales Forecasting\",\n",
      "                \"completed\": [\n",
      "                    \"Customer Segmentation\",\n",
      "                    \"Churn Prediction\"\n",
      "                ]\n",
      "            }\n",
      "        },\n",
      "        {\n",
      "            \"id\": 102,\n",
      "            \"name\": \"Bob\",\n",
      "            \"role\": \"Data Engineer\",\n",
      "            \"skills\": [\n",
      "                \"Spark\",\n",
      "                \"Hadoop\"\n",
      "            ],\n",
      "            \"projects\": {\n",
      "                \"current\": \"ETL Pipeline Optimization\",\n",
      "                \"completed\": [\n",
      "                    \"Data Warehouse Setup\"\n",
      "                ]\n",
      "            }\n",
      "        }\n",
      "    ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "# Load JSON file\n",
    "with open(\"data/company_data.json\", \"r\") as file:\n",
    "    data = json.load(file)\n",
    "\n",
    "# Convert json to string\n",
    "json_string = json.dumps(data, indent=4)\n",
    "\n",
    "print(json_string)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4a812b4-6c29-4ab3-8c42-7db11674b9f8",
   "metadata": {},
   "source": [
    "### **Iterating over JSON Data**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "632be62c-7ce8-41ad-bde7-6ddb10f53a11",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "company: TechCorp\n",
      "\n",
      "employees: [{'id': 101, 'name': 'Alice', 'role': 'Data Analyst', 'skills': ['Python', 'SQL'], 'projects': {'current': 'Sales Forecasting', 'completed': ['Customer Segmentation', 'Churn Prediction']}}, {'id': 102, 'name': 'Bob', 'role': 'Data Engineer', 'skills': ['Spark', 'Hadoop'], 'projects': {'current': 'ETL Pipeline Optimization', 'completed': ['Data Warehouse Setup']}}]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Print all key-value pairs\n",
    "for key, value in data.items():\n",
    "    print(f\"{key}: {value}\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aed6cd7e-ff2f-44d2-afbd-1413a80fbfb5",
   "metadata": {},
   "source": [
    "### **Extracting Data From Nested JSON**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "9345d34e-5ad0-43e8-8a6b-837c97799d3f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Company Name: TechCorp\n"
     ]
    }
   ],
   "source": [
    "# Extract company name\n",
    "\n",
    "print(\"Company Name:\", data[\"company\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a3b3642d-492b-4dfd-8395-575c0de36aba",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Employee: Alice\n",
      "Employee: Bob\n"
     ]
    }
   ],
   "source": [
    "# Extract all employees' names\n",
    "\n",
    "for emp in data[\"employees\"]:\n",
    "    print(\"Employee:\", emp[\"name\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b36fa7e1-c246-4164-9766-9e9e7d393f62",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bob's Current Project: ETL Pipeline Optimization\n"
     ]
    }
   ],
   "source": [
    "# Extract Bob's current project\n",
    "\n",
    "for emp in data[\"employees\"]:\n",
    "    if emp[\"name\"] == \"Bob\":\n",
    "        print(\"Bob's Current Project:\", emp[\"projects\"][\"current\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e116464-c159-43a9-86b2-3668a6f27d61",
   "metadata": {},
   "source": [
    "### **Adding and Updating Fields**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c3175b76-73a0-4c09-ace5-0fcae0dddfa3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Add Bob's email\n",
    "\n",
    "for emp in data[\"employees\"]:\n",
    "    if emp[\"name\"] == \"Bob\":\n",
    "        emp[\"email\"] = \"bob@techcorp.org\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "97918690-db53-4ce2-b400-af64d66331dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Updating Alice's role\n",
    "\n",
    "for emp in data[\"employees\"]:\n",
    "    if emp[\"name\"] == \"Alice\":\n",
    "        emp[\"role\"] = \"Senior Data Analyst\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "5ee2ff55-da8c-4d3f-a2f7-7e52f4b9e099",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Add a new employee\n",
    "\n",
    "new_employee = {\n",
    "    \"id\": 103,\n",
    "    \"name\": \"Charlie\",\n",
    "    \"role\": \"ML Engineer\",\n",
    "    \"skills\": [\"Python\", \"TensorFlow\", \"NLP\"],\n",
    "    \"projects\": {\n",
    "        \"current\": \"Chatbot Development\",\n",
    "        \"completed\": [\"Sentiment Analysis\"]\n",
    "    }\n",
    "}\n",
    "\n",
    "# Append new employee to the JSON data\n",
    "data[\"employees\"].append(new_employee)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9081d3e4-17a1-473c-81d6-889de552f92b",
   "metadata": {},
   "source": [
    "### **Handling Missing Keys using .get() Method**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "679d4e34-084f-4ed1-9510-31fb1858ae3c",
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'email'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[18], line 4\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[38;5;66;03m# Let's try to get the email ids of all the employees\u001b[39;00m\n\u001b[1;32m      3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m emp \u001b[38;5;129;01min\u001b[39;00m data[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124memployees\u001b[39m\u001b[38;5;124m\"\u001b[39m]:\n\u001b[0;32m----> 4\u001b[0m     \u001b[38;5;28mprint\u001b[39m(\u001b[43memp\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43memail\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m]\u001b[49m)\n",
      "\u001b[0;31mKeyError\u001b[0m: 'email'"
     ]
    }
   ],
   "source": [
    "# Let's try to get the email ids of all the employees\n",
    "\n",
    "for emp in data[\"employees\"]:\n",
    "    print(emp[\"email\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "1f03a920-f2cf-4ee4-9644-2b10a7c0e86e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Not Available\n",
      "bob@techcorp.org\n",
      "Not Available\n"
     ]
    }
   ],
   "source": [
    "for emp in data[\"employees\"]:\n",
    "    print(emp.get(\"email\", \"Not Available\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3759100a-f676-49ae-a7e0-e57fbee1d38c",
   "metadata": {},
   "source": [
    "### **Filtering JSON Data**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "7a0c3866-a915-4643-8474-1f0ffd571cfa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python Experts: ['Alice', 'Charlie']\n"
     ]
    }
   ],
   "source": [
    "# Get Employees Who Know Python\n",
    "\n",
    "python_experts = [emp[\"name\"] for emp in data[\"employees\"] if \"Python\" in emp[\"skills\"]]\n",
    "print(\"Python Experts:\", python_experts)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "adde07bd-a043-4f08-a3be-4678e70a569a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bob is working on ETL Pipeline Optimization\n"
     ]
    }
   ],
   "source": [
    "# Get Employees Working on a Specific Project\n",
    "\n",
    "target_project = \"ETL Pipeline Optimization\"\n",
    "for emp in data[\"employees\"]:\n",
    "    if emp[\"projects\"][\"current\"] == target_project:\n",
    "        print(emp[\"name\"], \"is working on\", target_project)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ef69b2fb-25f1-4ac5-a576-6854a6289800",
   "metadata": {},
   "source": [
    "### **Writing JSON Data Back to a File**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "afe98ece-2dd9-45bf-bb60-5506936ac954",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Updated JSON file saved successfully!\n"
     ]
    }
   ],
   "source": [
    "# Save back to JSON file\n",
    "with open(\"data/updated_company_data.json\", \"w\") as file:\n",
    "    json.dump(data, file, indent=4)\n",
    "\n",
    "print(\"Updated JSON file saved successfully!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67a2245e-42ec-4ab6-ad94-ffb1ea5e699a",
   "metadata": {},
   "source": [
    "## **Advanced JSON Operations**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7aa03124-85a8-475d-91e2-bed50455b627",
   "metadata": {},
   "source": [
    "### **Sorting JSON Data**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "350060af-307f-42ee-98b2-092f73f2d383",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[\n",
      "    {\n",
      "        \"id\": 101,\n",
      "        \"name\": \"Alice\",\n",
      "        \"role\": \"Senior Data Analyst\",\n",
      "        \"skills\": [\n",
      "            \"Python\",\n",
      "            \"SQL\"\n",
      "        ],\n",
      "        \"projects\": {\n",
      "            \"current\": \"Sales Forecasting\",\n",
      "            \"completed\": [\n",
      "                \"Customer Segmentation\",\n",
      "                \"Churn Prediction\"\n",
      "            ]\n",
      "        }\n",
      "    },\n",
      "    {\n",
      "        \"id\": 102,\n",
      "        \"name\": \"Bob\",\n",
      "        \"role\": \"Data Engineer\",\n",
      "        \"skills\": [\n",
      "            \"Spark\",\n",
      "            \"Hadoop\"\n",
      "        ],\n",
      "        \"projects\": {\n",
      "            \"current\": \"ETL Pipeline Optimization\",\n",
      "            \"completed\": [\n",
      "                \"Data Warehouse Setup\"\n",
      "            ]\n",
      "        },\n",
      "        \"email\": \"bob@techcorp.org\"\n",
      "    },\n",
      "    {\n",
      "        \"id\": 103,\n",
      "        \"name\": \"Charlie\",\n",
      "        \"role\": \"ML Engineer\",\n",
      "        \"skills\": [\n",
      "            \"Python\",\n",
      "            \"TensorFlow\",\n",
      "            \"NLP\"\n",
      "        ],\n",
      "        \"projects\": {\n",
      "            \"current\": \"Chatbot Development\",\n",
      "            \"completed\": [\n",
      "                \"Sentiment Analysis\"\n",
      "            ]\n",
      "        }\n",
      "    }\n",
      "]\n"
     ]
    }
   ],
   "source": [
    "sorted_employees = sorted(data[\"employees\"], key=lambda x: x[\"name\"])\n",
    "\n",
    "print(json.dumps(sorted_employees, indent=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e86f76d1-9b59-479f-ae04-f6c74564ab48",
   "metadata": {},
   "source": [
    "### **Merging Two JSON Objects**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "0ec8ae2d-3b2c-4871-84b7-7f57ed3167cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "    \"name\": \"Alice\",\n",
      "    \"age\": 25,\n",
      "    \"city\": \"New York\",\n",
      "    \"role\": \"Data Scientist\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "json1 = {\"name\": \"Alice\", \"age\": 25}\n",
    "json2 = {\"city\": \"New York\", \"role\": \"Data Scientist\"}\n",
    "\n",
    "merged_json = {**json1, **json2}\n",
    "\n",
    "print(json.dumps(merged_json, indent=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "251c3396-8675-4922-8245-d137ea0668b1",
   "metadata": {},
   "source": [
    "## **Handling JSON Data from APIs**\n",
    "\n",
    "Now, let’s fetch JSON from an API using Python's requests module."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53e37c38-75a5-423b-b701-69d303193311",
   "metadata": {},
   "source": [
    "### **Fetching JSON from a REST API**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "a90da074-14f8-4e42-a0e2-cb7bcc20ca44",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/kanavbansal/Developer/.env_jupyter/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "# Fetch JSON from API\n",
    "url = \"https://jsonplaceholder.typicode.com/users\"\n",
    "response = requests.get(url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "9aa9ec7d-9a83-4d34-9886-dff50c95017c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Type of 'user' object: <class 'list'>\n",
      "Number of users: 10\n",
      "{\n",
      "    \"id\": 1,\n",
      "    \"name\": \"Leanne Graham\",\n",
      "    \"username\": \"Bret\",\n",
      "    \"email\": \"Sincere@april.biz\",\n",
      "    \"address\": {\n",
      "        \"street\": \"Kulas Light\",\n",
      "        \"suite\": \"Apt. 556\",\n",
      "        \"city\": \"Gwenborough\",\n",
      "        \"zipcode\": \"92998-3874\",\n",
      "        \"geo\": {\n",
      "            \"lat\": \"-37.3159\",\n",
      "            \"lng\": \"81.1496\"\n",
      "        }\n",
      "    },\n",
      "    \"phone\": \"1-770-736-8031 x56442\",\n",
      "    \"website\": \"hildegard.org\",\n",
      "    \"company\": {\n",
      "        \"name\": \"Romaguera-Crona\",\n",
      "        \"catchPhrase\": \"Multi-layered client-server neural-net\",\n",
      "        \"bs\": \"harness real-time e-markets\"\n",
      "    }\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "# Convert response to JSON\n",
    "users = response.json()\n",
    "\n",
    "print(\"Type of 'user' object:\", type(users))\n",
    "\n",
    "# Print number of user's\n",
    "print(\"Number of users:\", len(users))\n",
    "\n",
    "# Print first user's details\n",
    "print(json.dumps(users[0], indent=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d670147c-9980-4656-98c8-4ca40ff52e19",
   "metadata": {},
   "source": [
    "### **Handling API Errors**\n",
    "\n",
    "APIs may fail due to **server errors or wrong URLs**. Always handle errors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "fa50082a-dd31-423a-83f2-49c20aaa8c43",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data fetched successfully!\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "url = \"https://jsonplaceholder.typicode.com/users\"\n",
    "response = requests.get(url)\n",
    "\n",
    "if response.status_code == 200:\n",
    "    data = response.json()\n",
    "    print(\"Data fetched successfully!\")\n",
    "else:\n",
    "    print(\"Error fetching data:\", response.status_code)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
